package main

import (
	"fmt"
	"net"
	"os"
)

func main() {
	//新建一个监听
	listener,err := net.Listen("tcp", "127.0.0.1:8888")
	ServerHandleError(err,"listener.Accept()")
	for{
		//通过监听来新建一个连接
		conn, e := listener.Accept()
		ServerHandleError(e, "listener.Accept()")
		//fmt.Println("这是for循环的东西")
		go ChatWith(conn)
	}
}

func ChatWith(conn net.Conn) {
	//客户端拿过来的数据存到buffer里
	buffer := make([]byte, 1024)
	for {
		//buffer里的数据丢给服务器读取
		n, err := conn.Read(buffer)
		ServerHandleError(err, "conn.Read(buffer)")

		//客户端读取的数据转换成string类型
		clientMsg := string(buffer[0:n])
		fmt.Printf("收到%v的消息:%s\n", conn.RemoteAddr(), clientMsg)

		if clientMsg != "bye" {
			conn.Write([]byte("已阅:" + clientMsg))
		} else {
			fmt.Println("客户端发送过来的字节长度:",len(clientMsg))
			_, _ = conn.Write([]byte("bye!"))
			break
		}
	}
	conn.Close()
	fmt.Printf("客户端%s已经断开连接", conn.RemoteAddr())
}

func ServerHandleError(err error, when string) {
	if err != nil {
		fmt.Println(err, when)
		os.Exit(1)
	}
}
